package com.downguys.tool.httptool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.client.AsyncRestTemplate;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * @author mingmin.zhou(弄死熊猫)
 * @mail 714387891@qq.com
 * @date 2017/1/4
 */
public class HttpUtil {

    public static final Logger LOGGER = LoggerFactory.getLogger(HttpUtil.class);

    /**
     * 发送http异步请求
     * @param path
     * @param params  第一位为请求方式，当第一位为post时，才有第二位，第二位为post请求的参数
     * @throws URISyntaxException
     */
    public static void asyncGetOrPostForJson(String path,Object... params) throws URISyntaxException {
        AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate();
        ListenableFuture<ResponseEntity<Object>> forEntity = null;
        if("post".equalsIgnoreCase(String.valueOf(params[0]))){
            forEntity = asyncRestTemplate.postForEntity(new URI(path), (HttpEntity<?>) params[1],Object.class);
        }else if ("get".equalsIgnoreCase(String.valueOf(params[0]))){
            forEntity = asyncRestTemplate.getForEntity(path,Object.class);
        }

        forEntity.addCallback(new ListenableFutureCallback<ResponseEntity<Object>>() {
            @Override
            public void onSuccess(ResponseEntity<Object> result) {
                LOGGER.info("--->async rest response success----, result = "+result.getBody());
            }

            @Override
            public void onFailure(Throwable t) {
                LOGGER.error("=====rest response faliure======",t);
            }
        });
    }

    /**
     * 发送http同步请求
     * @param path
     * @param params  第一位为请求方式，当第一位为post时，才有第二位，第二位为post请求的参数
     * @return
     * @throws URISyntaxException
     */
    public static ResponseEntity<Object> syncGetOrPostForJson(String path,Object... params) throws URISyntaxException {

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Object> resultEntity = null;
        if("post".equalsIgnoreCase(String.valueOf(params[0]))){
            resultEntity = restTemplate.postForEntity(new URI(path),params[1],Object.class);
        }else if ("get".equalsIgnoreCase(String.valueOf(params[0]))){
            resultEntity = restTemplate.getForEntity(path,Object.class);
        }

        return resultEntity;
    }


}
